package com.tengju.user.infrastructure.listener;

import com.tengju.data.domain.model.alert.AlertEvent;
import com.tengju.data.domain.model.alert.AlertService;
import com.tengju.user.domain.model.sign.StarSignChangeEvent;
import com.tengju.user.domain.model.sign.StarSignStepEnum;
import com.tengju.user.domain.model.star.StarUserFeatureRepository;
import com.tengju.user.domain.model.user.StarLevelEnum;
import com.tengju.user.domain.model.user.UserIdCode;
import com.tengju.user.domain.shared.JsonUtil;
import com.tengju.user.domain.shared.SpringEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * @author chenhang
 * @Date 2021/1/21
 */
@Slf4j
@Component
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class StarSignChangeListener implements ApplicationListener<SpringEvent>,DomainEventListener {

    private final StarUserFeatureRepository starUserFeatureRepository;
    private final AlertService alertService;

    @Override
    public void onApplicationEvent(SpringEvent springEvent) {
        StarSignChangeEvent starSignChangeEvent = checkDomainEvent(springEvent, StarSignChangeEvent.class);
        if (starSignChangeEvent == null) {
            return;
        }
        log.info("收到星级签约流程变更消息：{}", JsonUtil.toJSONString(starSignChangeEvent));
        try {
            UserIdCode idCode = UserIdCode.of(starSignChangeEvent.getIdCode());
            StarLevelEnum afterStarLevel = StarLevelEnum.parseByCode(starSignChangeEvent.getAfterStarLevel());
            StarSignStepEnum beforeStep = StarSignStepEnum.getByStep(starSignChangeEvent.getBeforeStep());
            StarSignStepEnum afterStep = StarSignStepEnum.getByStep(starSignChangeEvent.getAfterStep());
            boolean isAdd = (beforeStep == null);
            boolean isRemove = (afterStep == StarSignStepEnum.END || afterStep == StarSignStepEnum.TERMINATED);
            if (isAdd || isRemove) {
                if (isRemove) {
                    afterStarLevel = StarLevelEnum.NONE;
                }
                starUserFeatureRepository.insertOrUpdateInviteStarLevel(idCode,afterStarLevel,starSignChangeEvent.getUpdateBy());
            }
        } catch (Exception e) {
            log.error("星级签约流程变更监听失败" + JsonUtil.toJSONString(starSignChangeEvent),e);
            AlertEvent alertEvent = new AlertEvent("星级变更监听失败");
            alertEvent.addItem("内容",JsonUtil.toJSONString(starSignChangeEvent));
            alertEvent.addItem("异常",e.getMessage());
            alertService.alert(alertEvent);
        }
    }
}
